package com.frontop.terminal.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.frontop.terminal.entity.Message;
import com.frontop.terminal.model.bo.TerminalVersionBo;
import com.frontop.terminal.model.vo.RestResult;
import com.frontop.terminal.service.ICommandSerivce;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.WriteDataUtil;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * <p>
 * 程序更新
 * </P>
 *
 * @author :CCC
 * @since :2021-06-16 16:58:00
 **/
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Slf4j
public class ProcedureUpdateServiceImpl implements ICommandSerivce {

    public static void main(String[] args) {
        //创建临时文件记录版本号
        String tmpName = "version.tmp";
        createFile(tmpName);

        String json = ReadDataUtil.read(tmpName);
        System.out.println(json);
    }

    private static void createFile(String path) {
        File file = new File(path);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动应用程序
     * 以任务管理器方式打开应用
     *
     * @param programPath 应用路径
     */
    private void startProgram(String programPath) {
        log.info("启动应用程序：" + programPath);
        if (!StrUtil.isEmpty(programPath)) {
            try {
                Desktop.getDesktop().open(new File(programPath));
            } catch (Exception e) {
                e.printStackTrace();
                log.error("应用程序：" + programPath + "不存在！");
            }
        }
    }

    @Override
    public RestResult executeWork(Message message) {
        //如果具体命令为空不执行
        if (StrUtil.isEmpty(message.getCommand())) {
            return RestResult.failed("command 参数不能为空");
        }


        TerminalVersionBo terminalVersionBo = JSON.parseObject(message.getCommand(), TerminalVersionBo.class);

        //获取当前版本号对比，如果相等不更新
        String version = Objects.requireNonNull(ReadDataUtil.getTerminalConfig()).getVersion();
//        String version = "1.1.0";
        if (!StrUtil.isEmpty(version) && !terminalVersionBo.getVersion().equals(version)) {
            log.info("开始更新");

            //创建临时文件记录版本号
            String tmpName = "version.tmp";
            createFile(tmpName);
            WriteDataUtil.write(String.valueOf(terminalVersionBo.getId()), tmpName);

            //更新程序名称
            String updateProcedurePath = "terminal-agent-update.exe";
            startProgram(updateProcedurePath);
            log.info("启动更新程序，终端代理将停止运行");
            ThreadUtil.sleep(2000);
            System.exit(0);
        } else {
            log.info("版本相同，取消更新");
        }

        return RestResult.success();
    }
}
